<template>
  <el-tooltip
    placement="bottom"
    effect="light"
    popper-class="padding-10-15"
    raw-content
    :disabled="type !== 'dates' || calcContent === '' || showText"
    :content="calcContent"
  >
  <div style="width: 100%" class="cc-date">
    <span v-if="showText">{{calcContent || ''}}</span>
      <el-date-picker
        v-model="currValue"
        style="width: 100%"
        :type="type"
        :format="format"
        :value-format="valueFormat"
        :placeholder="placeholder"
        :disabled="calcDisabled"
        @change="handleChange"
        @blur="handleBlur"
      />
  </div>
  </el-tooltip>
</template>

<script setup>
import { ref, computed, watch, inject } from 'vue';
import { useDisabled } from "element-plus";

const emit = defineEmits(['change', 'blur']);
const props = defineProps({
  prop: {
    type: String,
    default: ''
  },
  options: Object,
  placeholder: String,
  type: {
    type: String,
    default: 'date'
  },
  format: {
    type: String,
    default: 'YYYY-MM-DD'
  },
  valueFormat: {
    type: String,
    default: 'YYYY-MM-DD'
  },
  showText: Boolean,
  disabled: Boolean,
});

const inputDisabled = useDisabled();
const currValue = ref();
const formData = inject('formData');
const type = ref(props.type);

const calcDisabled = computed(() => {
  return inputDisabled.value || props.disabled || false;
});

const calcContent = computed(() => {
  const dates = (formData.value[props.prop] || '').split(',')
  return dates.sort().join(' <br/>');
});

const handleChange = () => {
  if (type.value === 'dates') {
    formData.value[props.prop] = currValue.value ? currValue.value.join(',') : '';
  } else {
    formData.value[props.prop] = currValue.value || '';
  }
  emit('change');
};

const handleBlur = () => {
  if (type.value === 'dates') {
    formData.value[props.prop] = currValue.value ? currValue.value.join(',') : '';
  } else {
    formData.value[props.prop] = currValue.value || '';
  }
  emit('blur');
};

watch(() => formData.value[props.prop], () => {
  if (type.value === 'dates') {
    currValue.value = formData.value[props.prop] ? (formData.value[props.prop] || '').split(',') : [];
  } else {
    currValue.value = formData.value[props.prop] || '';
  }
}, {immediate: true});

watch(() => props, () => {
  if (props.format && props.format.indexOf('HH') >= 0) {
    type.value = 'datetime';
  } else {
    type.value = props.type || 'date';
  }
  if (type.value && type.value.startsWith('cc-')) {
    type.value = type.value.substring(3);
  }
}, {immediate: true, deep: true});
</script>